package com.yixun.qfbao.api.service.impl;

import com.yixun.qfbao.api.service.CustomerTKService;
import com.yixun.qfbao.apidto.GetCustomerPageReqDto;
import com.yixun.qfbao.common.model.PageDTO;
import com.yixun.qfbao.mapper.CustomerMapper;
import com.yixun.qfbao.model.Customer;
import com.yixun.qfbao.model.enums.DelFlagEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class CustomerTKServiceImpl implements CustomerTKService {

    @Autowired
    private CustomerMapper customerMapper;

    /**
     * 获取客户详情
     * @param customerId
     * @return
     */
    @Override
    public Customer getCustomerById(Long customerId) {
        return customerMapper.selectByPrimaryKey(customerId);
    }

    @Override
    public Customer saveOrEditCustomer(Customer customer) {
        if(Objects.isNull(customer.getId())){
            return customer;
        }
        Example example = new Example(Customer.class);
        example.createCriteria()
                .andIsNotNull("id")
                .andEqualTo("id", customer.getId());
        customerMapper.updateByExampleSelective(customer, example);
        return customerMapper.selectByPrimaryKey(customer.getId());
    }

    @Override
    public int getWeappCustomerCount(GetCustomerPageReqDto reqDto) {
        Example example = new Example(Customer.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("agentId", reqDto.getUserId());
        if(StringUtils.isNotBlank(reqDto.getSearchContent())){
            String condition = "(real_name like '%"+reqDto.getSearchContent()+"%' or main_mobile like '%"+reqDto.getSearchContent()+"%')";
            criteria.andCondition(condition);
        }
        criteria.andEqualTo("delFlag", DelFlagEnum.UNDEL.getNo());
        return customerMapper.selectCountByExample(example);
    }

    @Override
    public List<Customer> getWeappCustomerPage(GetCustomerPageReqDto reqDto, PageDTO pageDTO) {
        Example example = new Example(Customer.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("agentId", reqDto.getUserId());
        if(StringUtils.isNotBlank(reqDto.getSearchContent())){
            String condition = "(real_name like '%"+reqDto.getSearchContent()+"%' or main_mobile like '%"+reqDto.getSearchContent()+"%')";
            criteria.andCondition(condition);
        }
        criteria.andEqualTo("delFlag", DelFlagEnum.UNDEL.getNo());
        RowBounds rowBounds = new RowBounds(pageDTO.getOffset(), pageDTO.getPageSize());
        return customerMapper.selectByExampleAndRowBounds(example, rowBounds);
    }
}
